<?php
/**
 * Created by PhpStorm.
 * User: jswei
 * Date: 2018/4/24
 * Time: 8:54
 */

namespace app\admin\model;


use app\first\validate\HomeComView;

class HomeCom extends Base {
    /**
     * @param array $where
     * @param string $order
     * @param int $limit
     * @param string $field
     * @param bool $out
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($where = [], $order = '', $limit = 10, $field = '', $out = false){
        $list = $this
            ->field($field,$out)
            ->with(['member','article'])
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $page = $list->currentPage();
        $total = $list->total();
        foreach ($list as $k => $v){
            $list[$k]['sort_asc'] = $k + 1 + ($page-1) * $limit;
            $list[$k]['sort_desc'] = $total - ($page-1) * $limit - $k;
        }
        return $list;
    }

    public function getOneById($id = 0, $field = '*'){
        $info = $this
            ->field($field)
            ->with('article')
            ->find($id);
        return $info;
    }

    /**
     * @param $aid
     * @return bool
     */
    public function add($aid){
        $data = [
            'aid'=>$aid,
            'create_time'=>time()
        ];
        $valid = new HomeComView();
        if(!$valid->check($data)){
            return false;
        }
        if(!$this->save($data)){
            return false;
        }
        return true;
    }

    public function member(){
        return $this->hasOne('Member','id','mid')
            ->bind([
                'account',
                'nickname'
            ]);
    }

    public function article(){
        return $this->hasOne('Article','id','aid');
    }
}